package com.gt.interceptor;

import com.gt.contant.AjaxCode;
import com.gt.contant.CommonAjaxResult;
import com.gt.filter.MultiReadHttpServletRequestWrapper;
import com.gt.utils.DESUtil;
import com.gt.utils.PropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class PublicDecryptInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String resultBody = null;
        log.info("DecryptInterceptor请求地址:{}",request.getRequestURI());
        MultiReadHttpServletRequestWrapper requestWrapper = (MultiReadHttpServletRequestWrapper) request;
        // 获取解密的密钥
        // body解密
        try {
//            若有传入token，解析出openId放入json参数列表，方便日志记录请求的用户信息
            resultBody = DESUtil.decrypt(DESUtil.DES_KEY, requestWrapper.getBody().replaceAll("\"",""));
        } catch (Exception e) {
            PropertiesUtils.renderJson(request, response, new CommonAjaxResult(AjaxCode.DECRYPT_ERROR));
            return true;
        }
        requestWrapper.setBody(resultBody);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
